import zipfile
import rarfile
import StringIO

class imageLoader:
    def __init__(self, filename):
      self.fileList = {}
      self.filename = filename
      length = len(filename)
      ext = filename[length-3:length]
      ext = ext.lower()
      if (ext == 'zip') or (ext == "cbz"):
        self.imgFile = zipfile.ZipFile(filename)
      elif (ext == 'rar') or (ext == "cbr"):
        self.imgFile = rarfile.RarFile(filename)
      self.filesList = self.imgFile.namelist()
      self.removeDirectories()
      if self.filesList > 0:
        self.currentFile = 0;
        self.filesList.sort()

    def removeDirectories(self):
      for f in self.filesList:
        if (f.endswith('/')):
          self.filesList.remove(f)

    def getCurrentFile(self):
      return StringIO.StringIO(self.imgFile.read(self.filesList[self.currentFile]))

    def getNextFile(self):
      if (self.currentFile < self.filesList):
        self.currentFile += 1
        return self.getCurrentFile()
      else:
        return None

    def getPreviousFile(self):
      if (self.currentFile > 0):
        self.currentFile -= 1
        return self.getCurrentFile()
      else:
        return None

if __name__ == '__main__':
  il = imageLoader("lfg.cbz")
  if (il.getPreviousFile() != None):
    print "OK"
  else:
    print "error"
